<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="一、连接池概述 用池来管理Connection，这样可以重复使用Connection。有了池，所以我们就不用自己来创建Connection，而是通过池来获取Connection对象。当使用完Connection后，调用Connection的close()方法也不会真的关闭Connection，而是把Connection“归还”给池。池就可以再利用这个Connection对象了。    Java为数">
<meta name="keywords" content="java">
<meta property="og:type" content="article">
<meta property="og:title" content="JDBC连接池学习心得">
<meta property="og:url" content="http://gofarlau.oschina.io/2017/09/05/JDBC连接池学习/index.html">
<meta property="og:site_name" content="Gofar`s blog">
<meta property="og:description" content="一、连接池概述 用池来管理Connection，这样可以重复使用Connection。有了池，所以我们就不用自己来创建Connection，而是通过池来获取Connection对象。当使用完Connection后，调用Connection的close()方法也不会真的关闭Connection，而是把Connection“归还”给池。池就可以再利用这个Connection对象了。    Java为数">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://i.imgur.com/E93ALDL.png">
<meta property="og:image" content="https://i.imgur.com/IOgDD7W.png">
<meta property="og:image" content="https://i.imgur.com/nKJU4tc.png">
<meta property="og:updated_time" content="2017-09-05T02:55:56.814Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JDBC连接池学习心得">
<meta name="twitter:description" content="一、连接池概述 用池来管理Connection，这样可以重复使用Connection。有了池，所以我们就不用自己来创建Connection，而是通过池来获取Connection对象。当使用完Connection后，调用Connection的close()方法也不会真的关闭Connection，而是把Connection“归还”给池。池就可以再利用这个Connection对象了。    Java为数">
<meta name="twitter:image" content="https://i.imgur.com/E93ALDL.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://gofarlau.oschina.io/2017/09/05/JDBC连接池学习/"/>





  <title>JDBC连接池学习心得 | Gofar`s blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?50cbd9c6b412fe07e010e7417dc2e506";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Gofar`s blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://gofarlau.oschina.io/2017/09/05/JDBC连接池学习/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gofar Lau">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Gofar`s blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JDBC连接池学习心得</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-09-05T00:00:00+08:00">
                2017-09-05
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="一、连接池概述"><a href="#一、连接池概述" class="headerlink" title="一、连接池概述"></a>一、连接池概述</h3><ul>
<li>用池来管理Connection，这样可以重复使用Connection。有了池，所以我们就不用自己来创建Connection，而是通过池来获取Connection对象。当使用完Connection后，调用Connection的close()方法也不会真的关闭Connection，而是把Connection“归还”给池。池就可以再利用这个Connection对象了。</li>
</ul>
<p><img src="https://i.imgur.com/E93ALDL.png" alt=""></p>
<ul>
<li>Java为数据库连接池提供了公共的接口：javax.sql.DataSource，各个厂商需要让自己的连接池实现这个接口。这样应用程序可以方便的切换不同厂商的连接池！</li>
</ul>
<h3 id="二、DBCP连接池"><a href="#二、DBCP连接池" class="headerlink" title="二、DBCP连接池"></a>二、DBCP连接池</h3><p>DBCP也是一个开源的连接池，是Apache Common成员之一，在企业开发中也比较常见，tomcat内置的连接池。</p>
<h4 id="1-导入jar包"><a href="#1-导入jar包" class="headerlink" title="1.导入jar包"></a>1.导入jar包<br></h4><p><img src="https://i.imgur.com/IOgDD7W.png" alt=""></p>
<h4 id="2-编写工具类"><a href="#2-编写工具类" class="headerlink" title="2.编写工具类"></a>2.编写工具类</h4><p>连接数据库表的工具类, 采用DBCP连接池的方式来完成，Java中提供了一个连接池的规则接口 ：<br></p>
<ul>
<li><p>DataSource : 它是java中提供的连接池，作为 DriverManager 工具的替代项。在DBCP包中提供了DataSource接口的实现类，我们要用的具体的连接池 BasicDataSource类.</p>
<pre><code> public class JDBCUtils {
public static final String DRIVER = &quot;com.mysql.jdbc.Driver&quot;;
public static final String URL = &quot;jdbc:mysql://localhost:3306/daydb&quot;;
public static final String USERNAME = &quot;root&quot;;
public static final String PASSWORD = &quot;root&quot;;
/*
 * 创建连接池BasicDataSource
 */
public static BasicDataSource dataSource = new BasicDataSource();
//静态代码块
static {
//对连接池对象 进行基本的配置
dataSource.setDriverClassName(DRIVER); // 这是要连接的数据库的驱动
dataSource.setUrl(URL); //指定要连接的数据库地址
dataSource.setUsername(USERNAME); //指定要连接数据的用户名
dataSource.setPassword(PASSWORD); //指定要连接数据的密码
}
/*
 * 返回连接池对象
 */
public static DataSource getDataSource(){
    return dataSource;
    }
}
</code></pre><h4 id="3-工具类的使用"><a href="#3-工具类的使用" class="headerlink" title="3.工具类的使用"></a>3.工具类的使用</h4><p>  public class Demo {<br>  // 插入功能<br>  @Test<br>  public void insert(){</p>
<pre><code>try {
    //获取一个用来执行SQL语句的对象   QueryRunner
    QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
</code></pre><p>  String sql = “INSERT INTO zhangwu(name,money,parent) VALUES(?,?,?)”;</p>
<pre><code>    Object[] params = {&quot;股票收入&quot;, 5500, &quot;收入&quot;};    
     int line = qr.update(sql,params);
    //结果集处理
    System.out.println(&quot;line = &quot; + line);

} catch (SQLException e) {
    throw new RuntimeException(e);
}
</code></pre><p>  }</p>
<p>  //删除功能<br>  @Test<br>  public void delete(){</p>
<pre><code>try {
    //创建一个QueryRunner对象，用来完成SQL语句的执行
    QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
    //执行SQL语句
    String sql = &quot;DELETE FROM zhangwu WHERE name = ?&quot;;
    Object[] params = {&quot;股票收入&quot;};
    int line = qr.update(sql, params);
    //结果集的处理
    System.out.println(&quot;line=&quot;+line);

} catch (SQLException e) {
    throw new RuntimeException(e);
}
</code></pre><p>  }</p>
<p>  //更新功能<br>  @Test<br>  public void update(){</p>
<pre><code>try {
    //创建一个QueryRunner对象，用来完成SQL语句的执行
    QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
    //执行SQL语句
    String sql = &quot;UPDATE zhangwu SET money = money+1000 WHERE name=?&quot;;
    Object[] params = {&quot;股票收入&quot;};
    int line = qr.update(sql, params);
    //结果集的处理
    System.out.println(&quot;line=&quot;+line);

} catch (SQLException e) {
    throw new RuntimeException(e);
}
</code></pre><p>  }</p>
<p>  //查询功能,将结果集中第一条记录封装到一个指定的javaBean中。<br>  @Test<br>  public void search(){</p>
<pre><code>try{
    //获取QueryRunner 
    QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
    //执行SQL语句
    String sql = &quot;SELECT * FROM zhangwu&quot;;
    Object[] params = {};
    Product p = qr.query(sql, new BeanHandler&lt;Product&gt;(Product.class), params);
    //结果集处理
    System.out.println(p);

} catch(SQLException e){
    throw new RuntimeException(e);
    }
}
</code></pre><p>  }</p>
<h4 id="4-常见配置项"><a href="#4-常见配置项" class="headerlink" title="4.常见配置项"></a>4.常见配置项</h4><p><img src="https://i.imgur.com/nKJU4tc.png" alt=""></p>
</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/27/DBUtil学习心得/" rel="next" title="DBUtils 学习心得">
                <i class="fa fa-chevron-left"></i> DBUtils 学习心得
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/06/反射学习心得/" rel="prev" title="反射学习心得">
                反射学习心得 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMDM5NS82OTQ4"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Gofar Lau" />
          <p class="site-author-name" itemprop="name">Gofar Lau</p>
           
              <p class="site-description motion-element" itemprop="description">learning by doing.</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#一、连接池概述"><span class="nav-number">1.</span> <span class="nav-text">一、连接池概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、DBCP连接池"><span class="nav-number">2.</span> <span class="nav-text">二、DBCP连接池</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-导入jar包"><span class="nav-number">2.1.</span> <span class="nav-text">1.导入jar包</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-编写工具类"><span class="nav-number">2.2.</span> <span class="nav-text">2.编写工具类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-工具类的使用"><span class="nav-number">2.3.</span> <span class="nav-text">3.工具类的使用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-常见配置项"><span class="nav-number">2.4.</span> <span class="nav-text">4.常见配置项</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gofar Lau</span>

  
</div>


  <div class="powered-by">  个人专属</div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">博客 &mdash; byLGH </div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  








  





  

  

  

  

  

  

</body>
</html>
